package com.usian.springsecuritydemo01.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.springsecuritydemo01.entity.Menu;
import com.usian.springsecuritydemo01.entity.Role;
import com.usian.springsecuritydemo01.entity.Users;
import com.usian.springsecuritydemo01.mapper.UserInfoMapper;
import com.usian.springsecuritydemo01.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailService")
public class UserService implements UserDetailsService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       /* if (!"lzm".equals(username)){
            throw new UsernameNotFoundException("用户不存在");
        }
      String password="$2a$10$ycq8d41kVKoz6T5sNINN3u4Rjr7H2hS5mabf0fyG9gPUVhzSscwJW";
        return new User(username,password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,role"));*/
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Users users = usersMapper.selectOne(queryWrapper);
        if (users==null){
            throw new UsernameNotFoundException("用户不存在");
        }

        List<Role> roles = userInfoMapper.selectRoleByUserId(users.getId().longValue());

        List<Menu> menus = userInfoMapper.selectMenuByUserId(users.getId().longValue());
        List<GrantedAuthority> grantedAuthorities =new ArrayList<>();

        for (Role role:roles) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_"+role.getName());
            grantedAuthorities.add(simpleGrantedAuthority);
        }
        for (Menu menu:menus) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(menu.getPermission());
            grantedAuthorities.add(simpleGrantedAuthority);
        }
        //List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,role");
       return new User(username,users.getPassword(),grantedAuthorities);
    }
}
